<?php
/**
 * manager_role_relation
 * milloc
 * 2018-4-28
 */
namespace app\models\db;

use yii\db\ActiveRecord;
use app\models\db\Manager;
use app\models\db\Role;

class ManagerRoleRelation extends ActiveRecord
{
	public static function tableName()
	{
		return 't_manager_role_relation';
	}

	public function rules()
	{
		return [
			[['manager_id', 'role_id'], 'required', 'message' => 'manager_id or role_id was null'],
			[['manager_id', 'role_id'], 'unique', 'targetAttribute' => ['manager_id', 'role_id'], 'message' => 'key(manager_id, role_id) was not unique'],
			['manager_id', 'validateManagerId', 'message' => 'manager did not exist'],
			['role_id', 'validateRoleId', 'message' => 'role did not exist'],
		];
	}

	public function validateManagerId($attr, $param)
	{
		return boolval(Manager::find(['id' => $attr, 'is_deleted' => Manager::IS_DELETED_NO])->count());
	}

	public function validateRoleId($attr, $param)
	{
		return boolval(Role::find(['id' => $attr, 'is_deleted' => Role::IS_DELETED_NO])->count());
	}

	/**
	 * 保存manager_id
	 * 通过计算差集的方法
	 * @param  int $manager_id
	 * @param  array|int $role_id
	 * @return bool 如果没有修改原来的数据，也返回真
	 * @author milloc
	 * @date   2018-04-28
	 */
	public static function saveManagerRole($manager_id, $role_id)
	{
		if (!$manager_id || !$role_id) {
			return false;
		}

		$get_arr = is_array($role_id) ? $role_id : [$role_id];
		$ori_arr = self::find()->select('role_id')->where(['manager_id' => $manager_id])->asArray()->column();

		$save_arr = array_diff($get_arr, $ori_arr);
		$del_arr = array_diff($ori_arr, $get_arr);

		$res = true;
		if (!empty($save_arr) || !empty($del_arr)) {
			self::getDb()->transaction(function () use ($save_arr, $del_arr, $manager_id, &$res) {
				if (!empty($del_arr)) {
					$res = self::deleteAll(['manager_id' => $manager_id, 'role_id' => $del_arr]);
					if (!$res) {
						throw new \Exception('failed to delete');
						return;
					}
				}

				foreach ($save_arr as $save_id) {
					$obj = new ManagerRoleRelation;
					$obj->manager_id = $manager_id;
					$obj->role_id = $save_id;
					var_dump($save_id);
					if (!$obj->save()) {
						$res = false;
						throw new \Exception(implode('', $obj->firstErrors));
						break;
					}
				}
			});
		}

		return $res;
	}
}